package org.nextive.android.weightapp;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.nextive.android.weightapp.db.WeightDAO;
import org.nextive.android.weightapp.entities.Weight;
import org.nextive.android.weightapp.utils.Utils;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

public class LogWeight extends Activity 
{
	private Button buttonSettings;
	private Button buttonWeigtHistory;
	private EditText editTextWeight;
	private DatePicker datePicker;
	private Button buttonSaveWeight;
	
	private WeightDAO weightDAO;
	
	private long id;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.log_weight);
		
		weightDAO = new WeightDAO(this);
		weightDAO.open();
		
		buttonWeigtHistory = (Button) findViewById(R.id.buttonWeightHistory);
		buttonSettings = (Button) findViewById(R.id.buttonSettings);
		datePicker = (DatePicker) findViewById(R.id.datePickerDate);
		editTextWeight = (EditText) findViewById(R.id.editTextWeight);
		buttonSaveWeight = (Button) findViewById(R.id.buttonSaveWeight);
		
		fillData();
		
		buttonWeigtHistory.setOnClickListener(new OnClickListener() 
		{	
			@Override
			public void onClick(View v) 
			{
				Intent intentWeightHistory = new Intent(LogWeight.this, WeightHistory.class);
				startActivity(intentWeightHistory);
			}
		});
		
		buttonSettings.setOnClickListener(new OnClickListener() 
		{	
			@Override
			public void onClick(View v) 
			{
				Intent intentSettings = new Intent(LogWeight.this, InitialSetup.class);
				startActivity(intentSettings);
			}
		});
		
		buttonSaveWeight.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) 
			{
				saveWeight();
			}
		});
	}
	
	private void fillData()
	{
		Bundle extras = getIntent().getExtras();
		if (extras != null)
		{
			id = extras.getLong(WeightHistory.EXTRA_KEY_WEIGHT_ID);
			String date = extras.getString(WeightHistory.EXTRA_KEY_WEIGHT_DATE);
			double weightValue = extras.getDouble(WeightHistory.EXTRA_KEY_WEIGHT_WEIGHT);
			editTextWeight.setText(Utils.getRoundedWeight(this, weightValue));
			SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd");
			Date date_aux = null;
			try 
			{
				date_aux = dateformat.parse(date);
			} 
			catch (ParseException e) 
			{
				Log.d("Error parsing date", e.toString());
			}
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date_aux);		
			datePicker.updateDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
		}
	}
	
	private void saveWeight()
	{
		Weight weight = new Weight();
    	Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
		calendar.set(Calendar.MONTH, datePicker.getMonth());
		calendar.set(Calendar.YEAR, datePicker.getYear());
		SimpleDateFormat date = new SimpleDateFormat("yyyy/MM/dd");
		
		Cursor cursor = weightDAO.findByDate(date.format(calendar.getTime()));
		if (id <= 0 && cursor.getCount() > 0)
		{
			Toast.makeText(this, R.string.weight_recorded_selected_date, Toast.LENGTH_SHORT).show();
		}
		else
		{
			weight.setDate(date.format(calendar.getTime()));
			try
			{
				double weightValue = Double.parseDouble(editTextWeight.getText().toString());
				SharedPreferences settings = LogWeight.this.getSharedPreferences(InitialSetup.PREFERENCES_NAME, 0);
		        int unit = settings.getInt(InitialSetup.PREFERENCES_KEY_UNIT, 0);
		        String[] units = LogWeight.this.getResources().getStringArray(R.array.units);
		        if (units[unit].equals("Kilograms"))
				{
		        	weightValue = weightValue*2.20462262;
				}
		        DecimalFormat decimalFormat = new DecimalFormat("#.#");
		        weightValue = Double.parseDouble(decimalFormat.format(weightValue));
		        weight.setWeight(weightValue);
		        
		        if (id > 0)
		        {
		        	weight.setId(id);
		        	weightDAO.update(weight);
		   		 	Toast.makeText(this, R.string.weight_updated, Toast.LENGTH_SHORT).show();
		   		 	finish();
		        }
		        else
		        {
		        	weightDAO.insertWeight(weight);
		        	Toast.makeText(this, R.string.weight_saved, Toast.LENGTH_SHORT).show();
		        	Intent weighHistoryIntent = new Intent(LogWeight.this, WeightHistory.class);
					startActivity(weighHistoryIntent);
		        }
			}
			catch(NumberFormatException e)
			{
				Toast.makeText(this, R.string.error_number_format, Toast.LENGTH_SHORT).show();
				editTextWeight.setText(null);
			}
		}
		cursor.close();
	}
	
	@Override
	public void onBackPressed() 
	{
		finish();
		super.onBackPressed();
	}
	
	@Override
	protected void onDestroy() 
	{
		weightDAO.close();
		super.onDestroy();
	}
}
